/**
 * 接口通用配置
 */

import Vue from 'vue'
import axios from 'axios'
import ElementUI from 'element-ui'
import config from './index.js'
import cookieUtils from '@/config/cookieUtils'
/* ------------------------------ 网站baseURL ------------------------------ */
Vue.prototype.$axios = axios
Vue.prototype.host = config.host
axios.defaults.baseURL = config.apiURL

// http request 拦截器
axios.interceptors.request.use(
  config => {
    // config.headers['Tenant-Id'] = 'H101902'
    let accessToken = cookieUtils.get('jczc_curr_token')
    let userId = cookieUtils.get('jczc_curr_userid')
    let orgId = cookieUtils.get('jczc_curr_orgid')
    let tenantId = cookieUtils.get('jczc_curr_tenantid')

    if (accessToken && userId) {
      config.headers['Access-Token'] = accessToken
      config.headers['X-User-Account'] = userId
      config.headers['Current-Org-Id'] = orgId
      // config.headers['Tenant-Id'] = 'CXY0001'
      config.headers['Tenant-Id'] = tenantId
    }

    // 临时添加Tanant-Id
    // config.headers['Tenant-Id'] = tenantId
    config.headers['X-Client-Id'] = 'a91ffd2c9af244c7bf8c0dc120828e18'
    return config
  },
  err => {
    return Promise.reject(err)
  })

// http response 拦截器
axios.interceptors.response.use(
  response => {
    var serverResult = response.data.serverResult
    if (serverResult && serverResult.resultCode !== '200' && serverResult.resultCode !== '10007' && serverResult.resultCode !== '10008' && serverResult.resultCode !== '10010') {
      // var msg = serverResult.resultMessage
      // ElementUI.Message(
      //   {
      //     type: 'error',
      //     message: msg
      //   })
      return Promise.reject(response)
    }
    return response
  },
  error => {
    if (error.response && error.response.data) {
      var errorJson = error.response.data
      if (errorJson.resultCode && errorJson.resultCode === 4210) {
        ElementUI.Message(
          {
            type: 'error',
            message: '您的账号是退出状态，请重新登录！',
            onClose: function () {
              cookieUtils.set('jczc_curr_userid', '')
              cookieUtils.set('jczc_curr_roleid', '')

              location.reload()
            }
          })
        return
      }
    }
    return Promise.reject(error.response.data)
  })
export default axios
/* ------------------------------ Mock请求: 只在测试环境且请求以apiName结尾时生效 ------------------------------ */
